<template>
	<gui-page ref="guiPage" :customHeader="true">
		<template v-slot:gHeader> 
			<nav-bar-custom left-icon="left" :leftType="'1'"  @clickLeftBack="clickLeftBack" scanType="1" :title="$t('JsInternational.simpleProduction')"  :rightText="$t('distributedEnter.scanRecord')"
				@clickRight="clickRight"></nav-bar-custom>
		</template>
		<template v-slot:gBody>
			<view class="page-auto">
				<!-- 简单生产领料扫描条码模-->
				<view class="custom-form-card">
					<view class="custom-card-title">
						<text class="title-line"></text>
						<!-- {{$t('translationImage.simpleInformation')}} -->
						{{$t('JsInternational.simpleWarehousing')}}
					</view>
					<view class="custom-card-itemTwo" style="padding: 20rpx 0;">
						<text class="item-info-title" style="padding-right: 40rpx;"><text
							class="required-color">*</text>{{$t('distributedEnter.materialCoded')}}：</text>
						<uni-easyinput class="uni-mt-5" suffixIcon="scan" v-model="data.materialCode" focus
							type="search" :placeholder="$t('distributedOut.pleaseMaterial')" @confirm="confirm" @iconClick="iconClick">
						</uni-easyinput>
					</view>
					<view class="custom-card-itemTwo" style="padding: 20rpx 0;">
						<text class="item-info-title"><text class="required-color">*</text>{{$t('distributedOut.warehouse')}}：</text>
						<text>{{data.scanInfo.warehouseName}}</text>
					</view>
					<view class="custom-card-itemTwo" style="padding: 20rpx 0;">
						<text class="item-info-title"><text class="required-color">*</text>{{$t('setting.department')}}：</text>
						<superweiCombox style="text-align:right;" :candidates="data.selectList" :placeholder="$t('distributedEnter.placeholderTextChoose')"
							:isJSON="true" keyName="text" @select="select" v-model="data.deportment" ></superweiCombox>
					</view>
					<view class="custom-card-itemTwo" style="padding: 20rpx 0;">
						<text class="item-info-title" style="padding-right: 40rpx;">{{$t('hardware.inventoryQuantity')}}：<text style="color:black">{{data.totalNum}}</text></text>
						<!-- <uni-easyinput class="uni-mt-5" v-model="data.totalNum" type="number" :placeholder="$t('translationImage.pleaseScan')" disabled >
						</uni-easyinput> -->
					</view>
				</view>
				<!-- 当前扫描条码信息展示-->
				<view v-if="Object.keys(data.scanInfo).length" class="custom-form-card" >
					<uni-collapse v-model="data.cardValue">
						<uni-collapse-item titleBorder="none" :show-animation="true">
							<template v-slot:title>
								<view class="custom-card-title">
									<text class="title-line"></text>
									{{$t('distributedOut.atPresent')}}
								</view>
							</template>
							<view class="content" >
								<view class="custom-card-itemOne">
									<text class="item-info-title">{{$t('distributedEnter.materialCoded')}}：</text>{{data.scanInfo.barcode}}
								</view>
								<view class="custom-card-itemOne">
									<view class="card-item-50">
										<text class="item-info-title">{{$t('distributedEnter.materialCode')}}：</text>{{data.scanInfo.materialCode}}
									</view>
									<view class="card-item-50">
										<text class="item-info-title">{{$t('distributedEnter.materialName')}}：</text>{{data.scanInfo.materialName}}
									</view>
								</view>
								<view class="custom-card-itemOne">
									<text class="item-info-title">{{$t('distributedEnter.materialSpec')}}：</text>{{data.scanInfo.materialSpec}}
								</view>
								<view class="custom-card-itemOne">
									<view class="card-item-50">
										<text class="item-info-title">{{$t('distributedEnter.uom')}}：</text>{{data.scanInfo.unit}}
									</view>
									<view class="card-item-50">
										<text class="item-info-title">{{$t('distributedEnter.qty')}}：</text>{{data.scanInfo.currentQty}}
									</view>
								</view>
								<view class="custom-card-itemOne">
									<!-- <view class="card-item-50" style="width: 100%;">
										<text class="item-info-title">{{$t('distributedOut.warehouse')}}：</text>{{data.scanInfo.warehouseName}}
									</view> -->
									<view class="card-item-50" style="width: 100%;">
										<text class="item-info-title">{{$t('distributedOut.location')}}：</text>{{data.scanInfo.locationName}}
									</view>
								</view>
								<view class="custom-card-itemOne">
									<view class="card-item-50">
										<text class="item-info-title">{{$t('distributedOut.warehouse')}}：</text>{{data.scanInfo.warehouseName}}
									</view>
									<!-- <view class="card-item-50">
										<text class="item-info-title">{{$t('distributedOut.location')}}：</text>{{data.scanInfo.locationName}}
									</view> -->
								</view>
							</view>
						</uni-collapse-item>
					</uni-collapse>
				</view>
			
				<!-- 底部操作栏按钮 -->
				<view class="page-bottom">
					<view class="page-bottomBtn bottomBtn-bgcolor-green" @click="submit">
						{{$t('calendar.submit')}}
					</view>
				</view>

				<!-- 弹框填写数量 -->
				<!-- <uni-popup ref="inputDialog" type="center"> -->
					<!-- <view class="input-dialog-box">
						<view class="input-dialog-content">
							<view class="input-dialog-item">
								{{$t('distributedEnter.materialCode')}}:{{data.scanInfo.barcode}}
							</view>
							<view class="input-dialog-item">
								{{$t('distributedEnter.materialName')}}:{{data.scanInfo.materialName}}
							</view>
							<view class="input-dialog-item">
								{{$t('translationImage.currentNumbers')}}:{{data.scanInfo.currentQty}}
							</view> -->
							<!-- <view class="gui-form-item">
								<text style="color:brown">{{$t('distributedEnter.qty')}}：</text>
								<view>
									<input type="number" 
									class="gui-form-input" 
									v-model="data.scanInfo.inputNum" 
									name="name1" 
									:placeholder="$t('distributedEnter.pleaseMaterialQty')" />
								</view>
							</view> -->
						<!-- </view>
						<view class="input-dialog-footer">
							<view class="input-dialog-button" @click="cancelFn">
								{{$t('popup.cancel')}}
								</view>
							<view class="input-dialog-button dialog-button-left" @click="confirmFn">
								{{$t('popup.confirm')}}
							</view>
						</view>
					</view>
				</uni-popup> -->
			</view>
		</template>
	</gui-page>
</template>

<script setup>
	//引入文件
	import { navigate } from '@/utils/routerSkip.js';
	import { ref, reactive,onMounted ,computed,watch,toRaw} from "vue";
	import superweiCombox from '@/components/superweiCombox';
	import { getDataDictionaryFn } from '@/utils/index.js';
	import { simpleProductionInstock,wmsSelectWmsBarcodeInfo,getDataDictionary } from '@/api/api.js';
	import pdaScan from '@/hooks/pdaScan.js';
	import { useStore } from "vuex";
	import { basPdaOperationLogFn } from '@/utils/index.js';
	import { OPERATION_COMMIT, OPERATION_SCAN } from '@/constant/index.js'
	import { onBackPress } from '@dcloudio/uni-app';
	//JS国际化引入
	import { useI18n } from 'vue-i18n';
	components: {
		superweiCombox
	}
	const { t } = useI18n();
	
	let store = useStore();
	//定义变量
	let data = reactive({
		materialCode: "",
		warehouse:'',
		scanNumber:0,
		returnSpScanList:[], // 扫描纪录的存储数组
		scanInfo:{}, //当前扫描信息
		cardValue:['0'],
		selectList:[],
		deportment:"",//部门
		deportmentCode:"",//部门编码
	});
	
	data.scanList = computed(()=>{
		console.log(store.state.simpleWarehousingList,'data.scanList')
		return store.state.simpleWarehousingList
	})
	//入库数量的计算
	data.totalNum = computed(()=>{
		let total = 0;
		data.scanList.forEach(x => {
			total += Number(x.inputNum)
		}); 
		return total
	})

	//页面弹框输入数量使用的变量
	let inputDialog = ref(null);
	const {scan}=pdaScan();
	onBackPress((options) => {
		if (options.from == 'backbutton') {
			navBackCheck()
			return true;
		}
	})
	//导航栏左侧返回
	const clickLeftBack = () => {
		navBackCheck()
	}
	const navBackCheck = () =>{
		if(!data.scanList.length){
			uni.navigateBack({
				delta: 1
			});
			return true
		}
		uni.showModal({
			title: t('smashRemoval.warmPrompt'),
			content: t('materials.unsubmittedDataIn'),
			success: function (res) {
				if (res.confirm) {
					resetInitData()
					uni.navigateBack({
						delta: 1
					});
				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			}
		});
		
		return true
	}
	// 监听用户使用相机
	const iconClick= async (type)=>{
		if(type==='suffix'){
			let code=await scan();
			getCode(code,'scan')
		}
	}

	//扫描条码框
	const confirm = () => {
		getCode(data.materialCode,'keydown')
	}

	//获取code 
	const getCode= async (code,type)=>{
		// 存储扫描的的条码,通过barode去判断是否有重复
		let arr=data.scanList.filter(x=> x.barcode==code);
		if(arr.length>0){
			uni.showToast({title:t('smashRemoval.codesRepeatedly'),icon:'none'});
			return  
		}
		data.materialCode=code;
		let parmes = {
			barcode: code,
			selectType: 'productionInstock',
		}
		let res = await wmsSelectWmsBarcodeInfo(parmes)
		try {
			let inputParameter = JSON.stringify(parmes)
			let returnParameter = JSON.stringify(res)
			let operationPicture = '简单生产入库'
			let callInterface = res.rquestUrl
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode:res.status,//返回状态
				errorMessage:res.message,//错误信息
				isPass:res.status == 200 ? 'Y' : 'N',//是否成功 Y N
				operationType:OPERATION_SCAN
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) {
		}
		if(res.status==200){
			let bool = await filter(res.data)
			if(!bool){
				uni.showToast({title:t('smashRemoval.non-BOMMaterial'),icon:'none'});
			    return  
			}
			data.scanInfo=res.data;
			store.commit('addsimpleWarehousingList',data.scanInfo)
			// inputDialog.value.open();//打开弹框
			data.scanInfo.inputNum=res.data.currentQty; //弹框的数据

		}else{
			uni.showToast({title:res.message, icon:"none"})
		}
	}

	//调用getCode
	onMounted(()=>{
		uni.$on('scancodedate', (data) => {
			console.log('获取到的code：' + data.code)
			getCode(data.code, 'pda')
		})
		//加载页面获取字典项配置的部门
		getDataDictionary({
			code:'Deportment'
		}).then(res=>{
			res.forEach(x=>{
				data.selectList.push({
					text:x.text,
					value:x.value
				})
			})
		})
	})

	//选择部门的时候将value值赋值给部门绑定的值
	const select=(e)=>{
		data.deportment=e.text;
		data.deportmentCode=e.value;
	}

	const filter = async (data)=>{
		// 查询目的仓库
		let locationCapacity  = await getDataDictionaryFn('NotBomMaterial')
		let bool = false
		bool = locationCapacity.some((item)=>{
			return item.value == data.materialCode
		})
		return bool
	}
	// 弹框的取消按钮
	// const cancelFn = () => {
	// 	inputDialog.value.close();
	// }
	//弹框的确定按钮
	// const confirmFn = () => {
	// 	if(!data.scanInfo.inputNum){
	// 		uni.showToast({title:t('smashRemoval.quantityCannot'),icon:'none'})
	// 		return
	// 	}
	// 	if(data.scanInfo.inputNum>data.scanInfo.currentQty){
	// 		uni.showToast({title:t('smashRemoval.greaterThan'),icon:'none'})
	// 		data.scanInfo.inputNum=null
	// 		return
	// 	}
	// 	store.commit('addsimpleWarehousingList',data.scanInfo)

	// 	inputDialog.value.close();
	// }

	//页面跳转
	const  clickRight=()=>{
		navigate({
			url:'/pages/simpleWarehousing/simpleWarehousingRecord'
		})
	}

	//提交
	const submit = () => {
		//判断是否扫描了条码
		if(data.materialCode==""){
			uni.showToast({title:t('pageTranslation.plsScanBarcode'),icon:"none"});
			return
		}
		//判断是否选择了部门
		if(data.deportment==""){
			uni.showToast({title:t('pageTranslation.plsChooseDept'),icon:"none"});
			return
		}
		
		//转换传递数据的格式
		let tep = []
		data.scanList.forEach(x=>{
			tep.push({
				pickUpQty: x.inputNum,
				id: x.id,
				deptCode:data.deportmentCode
			})
		})
		//调用接口
		let parmes = {
			wmsBarcodes:tep
		}
		// 添加加载框
		uni.showLoading({
			title: 'loading',
			mask: true
		});
		simpleProductionInstock(parmes).then(res=>{
			try {
				let inputParameter = JSON.stringify(parmes)
				let returnParameter = JSON.stringify(res)
				let operationPicture = '简单生产入库'
				let callInterface = res.rquestUrl
				let opertionParmes = {
					inputParameter,
					returnParameter,
					operationPicture,
					callInterface,
					responseCode:res.status,//返回状态
					errorMessage:res.message,//错误信息
					isPass:res.status == 200 ? 'Y' : 'N',//是否成功 Y N
					operationType:OPERATION_COMMIT
				}
				basPdaOperationLogFn(opertionParmes)
			} catch (error) {
			}
			if(res.status==200){
				//隐藏加载框
				uni.hideLoading();
				uni.showToast({title:t('smashRemoval.submitSuccessfully')});//提交成功提示信息
				// 重置初始化数据
				resetInitData()
				
			}else {
				uni.showToast({ title: res.message, icon: "none" });
			}
		})
	}
	// 重置初始化数据
	const resetInitData = () => {
		data.materialCode="";
		store.commit("clearsimpleWarehousingList");//提交成功清空vuex中关于简单生产入库扫描的条码数据，同时也清空入库数量的数据
		data.deportmentCode="";
		data.warehouseName = ''
		data.deportment = ''
		data.scanInfo={} //当前扫描信息
	}
</script>

<style lang="scss" scoped>
</style>
